import { InfoScoreboard } from "@sapi-game/gameComponent/view/infoScoreboard";
import { Timer } from "@sapi-game/gameComponent/common/timer/timer";
import { Game, GameComponent } from "@sapi-game/main";
import { Duration } from "@sapi-game/utils";
import { EffectIds } from "@sapi-game/utils/vanila-data";
import { PillarOfFortuneMainState } from "../states/mainState";
import { PillarOfFortuneEvent } from "./events";

export class PillarOfFortuneDaemon extends GameComponent<PillarOfFortuneMainState> {
    override onAttach(): void {
        const timer = this.state.getComponent(Timer);
        this.subscribe(timer.events.tick, (t) => {
            console.log("aaa");
            this.updateSidebar(t.remainingTime);
        });
        //tick
        this.subscribe(
            Game.events.interval,
            () => {
                this.effect();
                this.checkEnd();
            },
            new Duration(40)
        );
    }

    effect() {
        this.context.players.forEach((p) =>
            p.addEffect(EffectIds.Saturation, 10)
        );
    }

    checkEnd() {
        const region = this.context.outSetRegion;
        let aliveCnt = 0;
        this.context.players.forEach((p) => {
            if (!p.alive) return;
            if (region.isInside(p.player.location)) {
                aliveCnt++;
            }
        });
        const timer = this.state.getComponent(Timer);
        if (aliveCnt <= 1 || timer.time == 0) {
            this.state.end();
        }
    }

    updateSidebar(time: number) {
        const alive = this.context.players.filter((p) => p.isValid && p.alive);
        //下一事件
        let eventText = "啥事没有";
        const event = this.state
            .getComponent(PillarOfFortuneEvent)
            .getNextEvent();
        if (event) {
            const min = Math.floor((time - event.time) / 60);
            const sec = Math.floor((time - event.time) % 60)
                .toString()
                .padStart(2, "0");
            eventText = event.event.name + " " + `§a${min}:${sec}`;
        }
        const lines = [
            "",
            "剩余玩家: §b" + alive.length,
            "",
            "下一事件:",
            "    " + eventText,
            "",
        ];
        this.state.getComponent(InfoScoreboard).updateLines(lines);
    }
}
